package team.fjut.cf.config.async;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 定义线程池和启动异步
 */

/**
 * @Configuration注明这是一个配置类，用以替代xml配置文件
 */
@Configuration
/**
 * https://blog.csdn.net/liuziteng0228/article/details/82825320
 * 异步执行注解
 */
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Value("${cf.config.threadPool.corePoolSize}")
    private int corePoolSize;

    @Value("${cf.config.threadPool.maxPoolSize}")
    private int maxPoolSize;

    @Value("${cf.config.threadPool.queueCapacity}")
    private int queueCapacity;

    @Bean
    @Override
    public Executor getAsyncExecutor() {
        // 定义线程池
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setThreadNamePrefix("async-exec-");
        taskExecutor.initialize();
        return taskExecutor;
    }
}
